#!/usr/bin/env node

/**
 * API版本管理CLI工具
 * 用于管理API版本的生命周期
 */

const fs = require('fs');
const path = require('path');

class VersionManagerCLI {
  constructor() {
    this.versionsDir = path.join(__dirname, '../src/modules');
    this.routesDir = path.join(__dirname, '../src/routes');
  }

  /**
   * 创建新的API版本
   */
  async createVersion(versionName, baseVersion = null) {
    console.log(`📦 Creating new API version: ${versionName}`);
    
    try {
      // 1. 创建routes版本目录
      const routeVersionDir = path.join(this.routesDir, versionName);
      if (!fs.existsSync(routeVersionDir)) {
        fs.mkdirSync(routeVersionDir, { recursive: true });
        console.log(`✅ Created routes directory: ${routeVersionDir}`);
      }

      // 2. 创建模块版本目录
      const modules = this.getExistingModules();
      for (const module of modules) {
        const moduleVersionDir = path.join(this.versionsDir, module, versionName);
        if (!fs.existsSync(moduleVersionDir)) {
          fs.mkdirSync(moduleVersionDir, { recursive: true });
          console.log(`✅ Created module version directory: ${moduleVersionDir}`);
          
          // 如果指定了基础版本，复制文件
          if (baseVersion) {
            await this.copyVersionFiles(module, baseVersion, versionName);
          } else {
            await this.createTemplateFiles(module, versionName);
          }
        }
      }

      // 3. 更新路由索引文件
      await this.updateRoutesIndex(versionName);
      
      console.log(`🎉 API version ${versionName} created successfully!`);
    } catch (error) {
      console.error(`❌ Error creating version ${versionName}:`, error.message);
    }
  }

  /**
   * 标记版本为已弃用
   */
  async deprecateVersion(versionName, sunsetDate) {
    console.log(`⚠️ Deprecating API version: ${versionName}`);
    
    try {
      // 更新版本配置
      const configPath = path.join(__dirname, '../config/api-version.config.js');
      // 这里应该更新配置文件中的版本状态
      
      console.log(`✅ Version ${versionName} marked as deprecated`);
      console.log(`📅 Sunset date: ${sunsetDate}`);
    } catch (error) {
      console.error(`❌ Error deprecating version ${versionName}:`, error.message);
    }
  }

  /**
   * 下线指定版本
   */
  async sunsetVersion(versionName) {
    console.log(`🌅 Sunsetting API version: ${versionName}`);
    
    try {
      // 备份版本文件
      await this.backupVersion(versionName);
      
      // 移除版本目录
      const routeVersionDir = path.join(this.routesDir, versionName);
      if (fs.existsSync(routeVersionDir)) {
        fs.rmSync(routeVersionDir, { recursive: true });
        console.log(`🗑️ Removed routes directory: ${routeVersionDir}`);
      }

      const modules = this.getExistingModules();
      for (const module of modules) {
        const moduleVersionDir = path.join(this.versionsDir, module, versionName);
        if (fs.existsSync(moduleVersionDir)) {
          fs.rmSync(moduleVersionDir, { recursive: true });
          console.log(`🗑️ Removed module version directory: ${moduleVersionDir}`);
        }
      }

      console.log(`✅ Version ${versionName} has been sunset`);
    } catch (error) {
      console.error(`❌ Error sunsetting version ${versionName}:`, error.message);
    }
  }

  /**
   * 显示版本状态
   */
  async showVersionStatus() {
    console.log('📊 API Version Status Report');
    console.log('================================');

    const versions = this.getExistingVersions();
    
    if (versions.length === 0) {
      console.log('⚠️  No versions found. Run "npm run version:create v1" to create the first version.');
      return;
    }

    for (const version of versions) {
      const status = this.getVersionStatus(version);
      console.log(`\n${version}:`);
      console.log(`  Status: ${status.status}`);
      console.log(`  Modules: ${status.modules.join(', ')}`);
      console.log(`  Endpoints: ${status.endpointCount}`);
      console.log(`  Files: ${status.files.join(', ')}`);
    }
  }

  /**
   * 生成迁移报告
   */
  async generateMigrationReport(fromVersion, toVersion) {
    console.log(`📋 Generating migration report: ${fromVersion} → ${toVersion}`);
    
    const report = {
      from_version: fromVersion,
      to_version: toVersion,
      breaking_changes: [],
      new_features: [],
      deprecated_features: [],
      migration_steps: []
    };

    // 分析两个版本之间的差异
    const fromFiles = this.getVersionFiles(fromVersion);
    const toFiles = this.getVersionFiles(toVersion);

    // 这里应该实现文件对比逻辑
    console.log('📄 Migration report generated');
    console.log(JSON.stringify(report, null, 2));
  }

  /**
   * 获取现有模块列表
   */
  getExistingModules() {
    if (!fs.existsSync(this.versionsDir)) {
      return [];
    }
    
    return fs.readdirSync(this.versionsDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name);
  }

  /**
   * 获取现有版本列表
   */
  getExistingVersions() {
    const versions = new Set();
    
    // 从 routes目录获取版本
    if (fs.existsSync(this.routesDir)) {
      const routeVersions = fs.readdirSync(this.routesDir, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory() && dirent.name.startsWith('v'))
        .map(dirent => dirent.name);
      routeVersions.forEach(v => versions.add(v));
    }
    
    // 从模块目录获取版本
    const modules = this.getExistingModules();
    for (const module of modules) {
      const modulePath = path.join(this.versionsDir, module);
      if (fs.existsSync(modulePath)) {
        const moduleVersions = fs.readdirSync(modulePath, { withFileTypes: true })
          .filter(dirent => dirent.isDirectory() && dirent.name.startsWith('v'))
          .map(dirent => dirent.name);
        
        moduleVersions.forEach(v => versions.add(v));
      }
    }
    
    return Array.from(versions).sort();
  }

  /**
   * 获取版本状态信息
   */
  getVersionStatus(version) {
    const modules = [];
    const files = [];
    let endpointCount = 0;
    
    // 检查模块中的版本
    const existingModules = this.getExistingModules();
    for (const module of existingModules) {
      const versionDir = path.join(this.versionsDir, module, version);
      if (fs.existsSync(versionDir)) {
        modules.push(module);
        
        // 统计文件
        const versionFiles = fs.readdirSync(versionDir)
          .filter(file => file.endsWith('.js'));
        files.push(...versionFiles.map(f => `${module}/${f}`));
        
        // 粗略统计端点数量（每个controller文件算作5个端点）
        const controllerFiles = versionFiles.filter(f => f.includes('controller'));
        endpointCount += controllerFiles.length * 5;
      }
    }
    
    // 检查路由版本
    const routeVersionDir = path.join(this.routesDir, version);
    if (fs.existsSync(routeVersionDir)) {
      const routeFiles = fs.readdirSync(routeVersionDir)
        .filter(file => file.endsWith('.js'));
      files.push(...routeFiles.map(f => `routes/${f}`));
    }
    
    // 确定状态
    let status = 'unknown';
    if (version === 'v1') {
      status = 'deprecated';
    } else if (version === 'v2') {
      status = 'stable';
    } else if (version === 'v3') {
      status = 'beta';
    }
    
    return {
      status,
      modules,
      files,
      endpointCount
    };
  }

  /**
   * 获取版本文件列表
   */
  getVersionFiles(version) {
    const files = [];
    
    // 获取模块文件
    const modules = this.getExistingModules();
    for (const module of modules) {
      const versionDir = path.join(this.versionsDir, module, version);
      if (fs.existsSync(versionDir)) {
        const moduleFiles = fs.readdirSync(versionDir)
          .filter(file => file.endsWith('.js'))
          .map(file => path.join(versionDir, file));
        files.push(...moduleFiles);
      }
    }
    
    // 获取路由文件
    const routeVersionDir = path.join(this.routesDir, version);
    if (fs.existsSync(routeVersionDir)) {
      const routeFiles = fs.readdirSync(routeVersionDir)
        .filter(file => file.endsWith('.js'))
        .map(file => path.join(routeVersionDir, file));
      files.push(...routeFiles);
    }
    
    return files;
  }

  /**
   * 备份版本
   */
  async backupVersion(version) {
    const backupDir = path.join(__dirname, '../backups', version);
    if (!fs.existsSync(backupDir)) {
      fs.mkdirSync(backupDir, { recursive: true });
    }
    
    const versionFiles = this.getVersionFiles(version);
    for (const file of versionFiles) {
      const relativePath = path.relative(path.join(__dirname, '..'), file);
      const backupFile = path.join(backupDir, relativePath);
      const backupFileDir = path.dirname(backupFile);
      
      if (!fs.existsSync(backupFileDir)) {
        fs.mkdirSync(backupFileDir, { recursive: true });
      }
      
      fs.copyFileSync(file, backupFile);
    }
    
    console.log(`💾 Backup created: ${backupDir}`);
  }

  /**
   * 复制版本文件
   */
  async copyVersionFiles(module, fromVersion, toVersion) {
    const fromDir = path.join(this.versionsDir, module, fromVersion);
    const toDir = path.join(this.versionsDir, module, toVersion);
    
    if (fs.existsSync(fromDir)) {
      const files = fs.readdirSync(fromDir);
      for (const file of files) {
        const fromFile = path.join(fromDir, file);
        const toFile = path.join(toDir, file);
        fs.copyFileSync(fromFile, toFile);
        console.log(`📋 Copied: ${file}`);
      }
    }
  }

  /**
   * 创建模板文件
   */
  async createTemplateFiles(module, version) {
    const versionDir = path.join(this.versionsDir, module, version);
    
    // 创建基础控制器模板
    const controllerTemplate = `const express = require('express');
const router = express.Router();
const ${module}Service${version.toUpperCase()} = require('./${module}.service');

/**
 * ${module.charAt(0).toUpperCase() + module.slice(1)} Controller ${version.toUpperCase()}
 */

// GET /${module}s
router.get('/', async (req, res, next) => {
  res.json({ message: 'Get all ' + module + 's - ' + version });
});

module.exports = router;`;

    fs.writeFileSync(path.join(versionDir, `${module}.controller.js`), controllerTemplate);
    
    // 创建基础服务模板
    const serviceTemplate = `/**
 * ${module.charAt(0).toUpperCase() + module.slice(1)} Service ${version.toUpperCase()}
 */
class ${module.charAt(0).toUpperCase() + module.slice(1)}Service${version.toUpperCase()} {
  constructor() {
    // Service initialization
  }
}

module.exports = ${module.charAt(0).toUpperCase() + module.slice(1)}Service${version.toUpperCase()};`;

    fs.writeFileSync(path.join(versionDir, `${module}.service.js`), serviceTemplate);
    
    console.log(`📝 Created template files for ${module} ${version}`);
  }

  /**
   * 更新路由索引文件
   */
  async updateRoutesIndex(newVersion) {
    // 这里应该更新 src/routes/index.js 文件
    console.log(`🔄 Updated routes index for version ${newVersion}`);
  }
}

// CLI命令处理
const cli = new VersionManagerCLI();
const command = process.argv[2];
const args = process.argv.slice(3);

switch (command) {
  case 'create':
    cli.createVersion(args[0], args[1]);
    break;
  case 'deprecate':
    cli.deprecateVersion(args[0], args[1]);
    break;
  case 'sunset':
    cli.sunsetVersion(args[0]);
    break;
  case 'status':
    cli.showVersionStatus();
    break;
  case 'migration-report':
    cli.generateMigrationReport(args[0], args[1]);
    break;
  default:
    console.log(`
📦 API Version Manager CLI

Usage:
  node scripts/version-manager.js <command> [options]

Commands:
  create <version> [baseVersion]     Create a new API version
  deprecate <version> <sunsetDate>   Mark version as deprecated  
  sunset <version>                   Remove deprecated version
  status                             Show all versions status
  migration-report <from> <to>       Generate migration report

Examples:
  node scripts/version-manager.js create v3 v2
  node scripts/version-manager.js deprecate v1 2024-12-31
  node scripts/version-manager.js status
`);
}

module.exports = VersionManagerCLI;